package com.chengcang.admin.modules.busi.controller;

import com.chengcang.admin.common.annotation.LogOperation;
import com.chengcang.admin.common.utils.DicTransLateUtil;
import com.chengcang.admin.common.utils.ExcelUtils;
import com.chengcang.admin.modules.busi.dto.BusiInvoiceHeadDTO;
import com.chengcang.admin.modules.busi.service.BusiInvoiceHeadService;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.admin.modules.sys.excel.BusiInvoiceHeadExcel;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.page.PageData;
import com.chengcang.common.utils.Result;
import com.chengcang.common.validator.AssertUtils;
import com.chengcang.common.validator.ValidatorUtils;
import com.chengcang.common.validator.group.AddGroup;
import com.chengcang.common.validator.group.DefaultGroup;
import com.chengcang.common.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


/**
 * 发票抬头
 *
 * @author zhanli
 * @since 1.0.0 2023-01-09
 */
@Slf4j
@RestController
@RequestMapping("sys/invoicehead")
@Api(tags = "发票抬头")
public class BusiInvoiceHeadController {
    @Autowired
    private BusiInvoiceHeadService busiInvoiceHeadService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
    public Result<PageData<BusiInvoiceHeadDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<BusiInvoiceHeadDTO> page = busiInvoiceHeadService.page(params);
        dictProcess(page);
        //设置字典转换
        return new Result<PageData<BusiInvoiceHeadDTO>>().ok(page);
    }

    protected void dictProcess(PageData<BusiInvoiceHeadDTO> page) {
        //字典处理
        for (BusiInvoiceHeadDTO dto : page.getList()) {
            try {
                BeanUtils.copyProperties(DicTransLateUtil.translate(dto, true, BusiInvoiceHeadDTO.class), dto);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new CustomException("字典转换异常！");
            }
        }
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<BusiInvoiceHeadDTO> get(@PathVariable("id") Long id) {
        BusiInvoiceHeadDTO data = busiInvoiceHeadService.get(id);

        return new Result<BusiInvoiceHeadDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    public Result save(@RequestBody BusiInvoiceHeadDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setTenantId(SecurityUser.getTenantId());
        busiInvoiceHeadService.save(dto);

        return new Result();
    }

    @GetMapping("defaultInvoiceHead/{id}")
    @ApiOperation("设置默认地址")
    @LogOperation("设置默认地址")
    public Result defaultAddress(@PathVariable String id){
        //效验数据
        AssertUtils.isNull(id, "id");

        busiInvoiceHeadService.setDefaultInvoiceHead(id);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    public Result update(@RequestBody BusiInvoiceHeadDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        dto.setDefaulted(null);
        dto.setDeleted(null);
        if (!Pattern.matches("^[a-zA-Z0-9]{1,20}$",dto.getInvoiceCode())){
            throw new CustomException("企业税号格式错误");
        }
        busiInvoiceHeadService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        busiInvoiceHeadService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<BusiInvoiceHeadDTO> list = busiInvoiceHeadService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, BusiInvoiceHeadExcel.class);
    }

}